package com.bussiness.activiti.controller;

import com.activiti.dto.ComplementTaskDto;
import com.activiti.util.ActivitiUtilService;
import com.alibaba.fastjson.JSONObject;
import com.bussiness.activiti.service.DeployMentService;
import com.common.response.ResponseBean;
import com.common.response.impl.BaseResponseImpl;
import com.common.util.JavaBeanUtil;
import com.common.util.mypage.Pages;
import com.security.auth.UserDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags={"activiti任务相关"})
@RequestMapping("/taskBase")
public class TaskBaseController extends BaseResponseImpl {

    @Autowired
    private DeployMentService deployMentService;

    @Autowired
    private ActivitiUtilService activitiUtilService;

    @RequestMapping(value = "/taskList", method = RequestMethod.GET)
    @ApiOperation(value = "待审批列表")
    public ResponseBean taskList(Integer pageSize, Integer pageNumber) {
        try {
            /**用户所在组，根据实际情况获取，也可以直接定义用户,这里直接固定
             * 第二种方式，根据打印sql修改为自己的sql来直接查询数据库，这样可以直接跟自己的权限联系起来*/
            List<String> arrayList = new ArrayList<>();
            arrayList.add("经理组");

            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserDetail userDetail = (UserDetail)  authentication.getPrincipal();
            String userName = userDetail.getUsername();

            List<Task>  taskList =activitiUtilService.userList(userName, null);
            // 循环转换数据
            List<Map<String, Object>> listMap = new ArrayList<>();
            String[] ps = { "id", "name", "processInstanceId", "createTime", "processVariables", "taskLocalVariables", "description", "owner",
            "processDefinitionId"};
            for (Task pd : taskList) {
                Map<String, Object> map = JavaBeanUtil.obj2map(pd, ps);
                listMap.add(map);
            }
            Pages pages = new Pages(pageNumber, pageSize, listMap);
            return  successData(pages);
        }catch (Exception e){
            e.printStackTrace();
            return error();
        }
    }

    @RequestMapping(value = "/historProcessList", method = RequestMethod.GET)
    @ApiOperation(value = "个人任务列表")
    public ResponseBean historProcessList(Integer pageSize, Integer pageNumber){
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserDetail userDetail = (UserDetail)  authentication.getPrincipal();

            List<HistoricProcessInstance>  taskList = activitiUtilService.getHistorProcess(String.valueOf(userDetail.getId()));
            for(int i=0;i<taskList.size();i++){
                HistoricProcessInstance historicProcessInstance = taskList.get(i);
                System.out.println(JSONObject.toJSON(historicProcessInstance.getProcessVariables()).toString() );
            }
            Pages pages = new Pages(pageNumber, pageSize, taskList);
            return  successData(pages);
        }catch (Exception e){
            e.printStackTrace();
            return error();
        }
    }

    @RequestMapping(value = "/showImg", method = RequestMethod.GET)
    @ApiOperation(value = "根据流程id获取图片")
    public void showImg(@RequestParam("processInstanceId") String processInstanceId){
        HttpServletResponse response = getResponse();
        System.out.println("[开始]-获取流程图图像");
        // 设置页面不缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            // 获取流程图图像字符流
            InputStream imageStream = activitiUtilService.getActivitiProccessImage(processInstanceId);

            response.setContentType("image/png");
            OutputStream os = response.getOutputStream();
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = imageStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            imageStream.close();
            System.out.println("[完成]-获取流程图图像");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("【异常】-获取流程图失败！" + e.getMessage());
        }
    }

    @RequestMapping(value = "/getVariableByTaskId", method = RequestMethod.GET)
    @ApiOperation(value = "流程参数")
    public ResponseBean getVariableByTaskId(String taskId){
        try {
            Map<String, Object> result = activitiUtilService.getVariablesByTaskId(String.valueOf(taskId));
            return  successData(result);
        }catch (Exception e){
            e.printStackTrace();
            return error();
        }
    }

    @RequestMapping(value = "/complementTask", method = RequestMethod.PUT)
    @ApiOperation(value = "审核通过任务")
    public ResponseBean complementTask(@RequestBody ComplementTaskDto complementTaskDto){
        try {
            UserDetail userDetail = getUserDetail();
            activitiUtilService.complementTask(String.valueOf(userDetail.getId()), complementTaskDto.getTaskId(),
                    complementTaskDto.getRemark());
            return success();
        } catch (Exception e){
            e.printStackTrace();
            return error();
        }
    }

    @RequestMapping(value = "/getVariblesByProcessId", method = RequestMethod.GET)
    @ApiOperation(value = "根据processId获取信息")
    public ResponseBean getVariblesByProcessId(String processInstanceId){
        try {
            Map<String, Object> resultMap = activitiUtilService.getVariblesByProcessId(processInstanceId);
            return successData(resultMap);
        } catch (Exception e){
            e.printStackTrace();
            return error();
        }
    }


    public UserDetail getUserDetail(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetail userDetail = (UserDetail)  authentication.getPrincipal();
        return userDetail;
    }

}
